package JUC;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author 豆包LU
 * @date 2023/5/8 11:50
 */
public class DelayQueueExample {

    public static void main(String[] args) throws InterruptedException {
        // 创建 DelayQueue 对象
        DelayQueue<MyDelayedObject> queue = new DelayQueue<>();

        // 向队列中添加元素
        queue.put(new MyDelayedObject("obj1", 1000));
        queue.put(new MyDelayedObject("obj2", 2000));
        queue.put(new MyDelayedObject("obj3", 3000));

        // 从队列中取出元素
        System.out.println(queue.take().getName()); // 等待 1 秒后输出 obj1
        System.out.println(queue.take().getName()); // 再等待 1 秒后输出 obj2
        System.out.println(queue.take().getName()); // 最后等待 1 秒后输出 obj3
    }

    /**
     * 实现 Delayed 接口的自定义类
     */
    static class MyDelayedObject implements Delayed {
        private String name; // 对象名称
        private long delayTime; // 延迟时间
        private long expireTime; // 到期时间

        public MyDelayedObject(String name, long delayTime) {
            this.name = name;
            this.delayTime = delayTime;
            this.expireTime = System.currentTimeMillis() + delayTime;
        }

        /**
         * 获取元素的剩余延迟时间
         */
        @Override
        public long getDelay(TimeUnit unit) {
            long diff = expireTime - System.currentTimeMillis();
            return unit.convert(diff, TimeUnit.MILLISECONDS);
        }

        /**
         * 比较元素的延迟时间
         */
        @Override
        public int compareTo(Delayed o) {
            if (this.expireTime < ((MyDelayedObject) o).expireTime) {
                return -1;
            } else if (this.expireTime > ((MyDelayedObject) o).expireTime) {
                return 1;
            }
            return 0;
        }

        public String getName() {
            return name;
        }
    }
}

